import React, { useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Modal, Row, Col, List, Typography, Button, Space, Carousel, Statistic } from 'antd';
import { useIntl, history, connect, utils } from 'umi';
import Categories from '@/pages/admin/categories';
import request from 'umi-request';
import {
  TagOutlined,
  FieldTimeOutlined,
  UserOutlined,
  FireTwoTone,
  ArrowRightOutlined,
} from '@ant-design/icons';
import { createFromIconfontCN } from '@ant-design/icons';
import 'intro.js/introjs.css';
import 'intro.js/themes/introjs-modern.css';
import IntroJs from 'intro.js';
import NewGuider from '@/components/NewGuider';
import DocHelper from '@/components/DocHelper';
import icon_chuku from '@/assets/icon_chuku.svg';
import icon_ruku from '@/assets/icon_ruku.svg';
import icon_setting from '@/assets/icon_setting.svg';
import icon_order from '@/assets/icon_order.svg';
import icon_po from '@/assets/icon_po.svg';
import icon_prod from '@/assets/icon_prod.svg';
import icon_insp from '@/assets/icon_insp.svg';
import icon_fin from '@/assets/icon_fin.svg';
import icon_part from '@/assets/icon_part.svg';
import style from './Welcome.less';
import EChartYibiao from './Charts/EchartYibiao';
import EchartInOut from './Charts/EchartInOut';
import type { CurrentUser } from '@/models/user';
import { getTimeState } from '@/utils/utils';

const { Text } = Typography;
// const cmsUrl = 'https://www.oplug.cn:5001';
// const apiKey = '619f1088-c883-4c2b-b9ab-11b1a982da08';
export interface FCProps {
  currentConfig: any;
  currentTenant: any;
  currentUser?: CurrentUser;
}
const WelcomeView: React.FC<FCProps> = (props: FCProps) => {
  const intl = useIntl();
  const [current, setCurrent] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [visible2, setVisible2] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<any>([]);
  const [userMenus, setUserMenus] = useState<any>([]);
  const [myIntro, setMyIntro] = useState<any>({});
  const [freshNum, setFreshNum] = useState<any>(1);
  const [chartData, setChartData] = useState<any>({});
  const [chartData2, setChartData2] = useState<any>({});
  const [sysConfig, setSysConfig] = useState<any>({});
  const [helloStr, setHelloStr] = useState<string>('');

  const switchModal = (v: boolean) => {
    setVisible(v);
  };
  const switchModal2 = (v: boolean, item: any = null) => {
    setCurrent(item);
    setVisible2(v);
  };
  const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_1059428_447vdgava57.js',
  });
  const startIntro = () => {
    const intro1 = IntroJs('#root');
    setMyIntro(intro1);
    intro1
      .setOptions({
        prevLabel: intl.formatMessage({ id: 'pages.intro.prev' }),
        nextLabel: intl.formatMessage({ id: 'pages.intro.next' }),
        skipLabel: intl.formatMessage({ id: 'pages.intro.skip' }),
        doneLabel: intl.formatMessage({ id: 'pages.intro.done' }),
      })
      .oncomplete(function () {})
      .onexit(function () {
        localStorage.setItem('welcomeGuide', 'ok');
      })
      .start();
  };
  const newGuider = () => {
    localStorage.removeItem('welcomeGuide');
    startIntro();
  };
  const contentStyle: React.CSSProperties = {
    height: '100%',
    padding: '30px',
  };
  const tStyle: React.CSSProperties = {
    color: '#364d79',
    fontWeight: 'bold',
    marginBottom: '5px',
  };
  const hStyle: React.CSSProperties = {
    height: '64px',
    overflow: 'hidden',
  };
  const pStyle: React.CSSProperties = {
    textAlign: 'right',
  };
  const cardStyle: React.CSSProperties = {
    backgroundColor: '#FFFFFF',
    padding: '10px',
    height: 210,
    overflow: 'hidden',
  };
  React.useEffect(() => {
    setHelloStr(getTimeState);
    setInterval(function () {
      setHelloStr(getTimeState);
    }, 30000);
    setLoading(true);
    const guider = localStorage.getItem('welcomeGuide');
    if (!guider || guider != 'ok') {
      startIntro();
    }
    // request
    //   .post(cmsUrl + '/api/v1/contents', {
    //     params: { apiKey },
    //     data: {
    //       siteId: 1,
    //       channelId: 1650,
    //       page: 1,
    //       perPage: 10,
    //       wheres: [
    //         {
    //           column: 'recommend',
    //           operator: '=',
    //           value: 'true',
    //         },
    //       ],
    //     },
    //   })
    //   .then(function (response) {
    //     setLoading(false);
    //     setDataSource(response.contents);
    //     console.log(response.contents);
    //   })
    //   .catch(function (error) {
    //     console.log(error);
    //   });

    request('/api/services/app/Article/GetNotice', {
      method: 'GET',
      params: {
        rec: 1,
        cate: 'ERP',
        skipCount: 0,
        maxResultCount: 5,
      },
    }).then((response) => {
      if (response.result) {
        setLoading(false);
        setDataSource(response.result.items);
        setFreshNum(freshNum + 1);
      }
    });

    // request('/api/services/app/SysConfig/GetConfig', {
    //   method: 'GET',
    // }).then((response) => {
    //   if (!response.result) {
    //     history.push('./InitWizard');
    //   } else {
    //     setSysConfig(response.result);
    //   }
    // });

    if (!props.currentConfig) {
      history.push('./InitWizard');
    } else {
      setSysConfig(props.currentConfig);
    }

    let year = new Date().getFullYear();
    request('/api/services/app/SysConfig/GetStatistic', {
      method: 'GET',
      params: { year },
    }).then((response) => {
      if (response.result) {
        setChartData(response.result);
        setLoading(false);
      }
    });
    request('/api/services/app/SysConfig/GetStatistic', {
      method: 'GET',
      params: {
        year: year - 1,
      },
    }).then((response) => {
      if (response.result) {
        setChartData2(response.result);
      }
    });

    request
      .get('/api/services/app/Module/GetUserFavMenu', {
        params: { mType: 'FavMenu' },
      })
      .then((response) => {
        const result = response.result;
        setUserMenus(result);
      });
  }, []);
  return (
    <PageContainer title={false} breadcrumbRender={false} ghost>
      <Row gutter={[16, 16]}>
        <Col
          xs={{ span: 24 }}
          sm={{ span: 12 }}
          md={{ span: 12 }}
          lg={{ span: 12 }}
          xl={{ span: 6 }}
          xxl={{ span: 6 }}
        >
          <div style={cardStyle}>
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <Space key="S1">
                  <Text strong>{sysConfig.companyName}</Text>
                  <NewGuider
                    key="1"
                    callback={() => newGuider()}
                    dataStep="1"
                    dataIntro="您好! 欢迎使用OPERP,初次使用我们的软件,让小O来指引你吧。"
                  />
                  <DocHelper page="gncidv" />
                </Space>
                <p>
                  Hello! {props.currentUser?.name}, {helloStr}
                </p>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={12}>
                <Card>
                  <Statistic
                    title={intl.formatMessage({id:'pages.myBanlance'})}
                    value={sysConfig.balance}
                    precision={2}
                    valueStyle={{ color: '#3f8600' }}
                    prefix="￥"
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card>
                  <Statistic
                    title={intl.formatMessage({id:'pages.smsCount'})}
                    value={sysConfig.smS_TotalNum}
                    precision={0}
                    valueStyle={{ color: '#cf1322' }}
                  />
                </Card>
              </Col>
            </Row>
          </div>
        </Col>
        <Col
          xs={{ span: 24 }}
          sm={{ span: 12 }}
          md={{ span: 12 }}
          lg={{ span: 12 }}
          xl={{ span: 4 }}
          xxl={{ span: 4 }}
        >
          <div style={cardStyle} data-step="6" data-intro="您可以在这里查看产品所使用的存储容量。">
            <EChartYibiao height={210} data={chartData} freshNum={freshNum} text={intl.formatMessage({id:'pages.storageCapacity'})} />
          </div>
        </Col>
        <Col
          xs={{ span: 24 }}
          sm={{ span: 12 }}
          md={{ span: 12 }}
          lg={{ span: 12 }}
          xl={{ span: 6 }}
          xxl={{ span: 6 }}
        >
          <div
            style={cardStyle}
            data-step="5"
            data-intro="这里是统计的企业近一年来的年产值、销售和采购额。"
          >
            <EchartInOut
              height={190}
              data={chartData}
              data2={chartData2}
              freshNum={freshNum}
              text={intl.formatMessage({id:'pages.yearTabulate'})}
            />
          </div>
        </Col>
        <Col
          xs={{ span: 24 }}
          sm={{ span: 12 }}
          md={{ span: 12 }}
          lg={{ span: 12 }}
          xl={{ span: 8 }}
          xxl={{ span: 8 }}
          data-step="4"
          data-intro="OPERP会不定期发布动态，您可以通过这里了解OPERP所有关于软件更新、产品动态、以及使用帮助方面的消息。"
        >
          <div style={cardStyle}>
            <Carousel dotPosition="bottom" autoplay>
              {dataSource.map((element: any) => (
                <div key={element.id}>
                  <div style={contentStyle}>
                    <p style={tStyle}>
                      <FireTwoTone twoToneColor="#eb2f96" hidden={!element.isHot} />
                      {element.title}
                    </p>
                    <p style={hStyle}>{element.summary}</p>
                    <div style={pStyle}>
                      <Button
                        type="primary"
                        icon={<ArrowRightOutlined />}
                        onClick={() => window.open(element.extendAttr, '_blank')}
                      >
                        {intl.formatMessage({id:'pages.viewDetail'})}
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </Carousel>
          </div>
        </Col>
        <Col
          span={24}
          data-step="2"
          data-intro="这里是ERP软件的主菜单，您可以快速访问ERP内主要功能。"
        >
          <Card>
            <Row gutter={16}>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/saleorder/orderEntry')}
              >
                <div className={style.funlist}>
                  <img src={icon_order} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.saleorder',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/purchase/poEntry')}
              >
                <div className={style.funlist}>
                  <img src={icon_po} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.purchase',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/part/partEntry')}
              >
                <div className={style.funlist}>
                  <img src={icon_part} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.PartEntry',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/part/rcvEntry')}
              >
                <div className={style.funlist}>
                  <img src={icon_ruku} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.RcvEntry',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/manufacture/jobEntry')}
              >
                <div className={style.funlist}>
                  <img src={icon_prod} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.manufacture',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/Inspect/inspEntry')}
              >
                <div className={style.funlist}>
                  <img src={icon_insp} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.InspEntry',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/part/shipEntry')}
              >
                <div className={style.funlist}>
                  <img src={icon_chuku} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.ShipEntry',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/Finance/FinRcvPay')}
              >
                <div className={style.funlist}>
                  <img src={icon_fin} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.FinanceReport',
                    })}
                  </p>
                </div>
              </Col>
              <Col
                xs={{ span: 8 }}
                sm={{ span: 4 }}
                md={{ span: 4 }}
                lg={{ span: 2 }}
                xl={{ span: 2 }}
                xxl={{ span: 2 }}
                onClick={() => history.push('/admin/sysconfig')}
              >
                <div className={style.funlist}>
                  <img src={icon_setting} />
                  <p>
                    {intl.formatMessage({
                      id: 'pages.sysConfig',
                    })}
                  </p>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col span={24}>
          <Card
            title={intl.formatMessage({
              id: 'pages.welcome.quickmenu',
              defaultMessage: 'Quick Menu',
            })}
          >
            <List
              data-step="7"
              data-intro="您可以把自己常用的菜单设置到快捷入口这边，方便您快速访问。"
              grid={{
                gutter: 16,
              }}
              dataSource={userMenus}
              renderItem={(item: any) => (
                <List.Item>
                  <Button
                    size="large"
                    type="default"
                    //href={item.modulePath}
                    onClick={() => history.push(item.modulePath)}
                    block
                  >
                    <IconFont type={item.logo} />
                    {intl.formatMessage({
                      id: item.description,
                    })}
                  </Button>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
      <Modal
        title={intl.formatMessage({
          id: 'pages.menu',
          defaultMessage: 'Menu',
        })}
        visible={visible}
        onCancel={() => switchModal(false)}
        footer={null}
        destroyOnClose
      >
        <Categories layout="Menu" size="small" />
      </Modal>
      <Modal
        title={current.title}
        visible={visible2}
        onCancel={() => switchModal2(false, current)}
        footer={null}
        width={1000}
        style={{ top: 20 }}
      >
        <Text type="secondary">
          <FieldTimeOutlined /> {current.lastEditDate}，<UserOutlined /> {current.addUserName}，
          <TagOutlined /> {current.tags}
        </Text>
        <div
          style={{ height: 500, overflow: 'auto' }}
          dangerouslySetInnerHTML={{ __html: current.content }}
        />
      </Modal>
    </PageContainer>
  );
};
export default connect(({ user }: API.IConnectState) => ({
  currentConfig: user.currentConfig,
  currentTenant: user.currentTenant,
  currentUser: user.currentUser,
}))(WelcomeView);
